package com.tuyrt.hi.hiitem.activity

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.tuyrt.hi.hiitem.fragment.FirstFragment
import com.tuyrt.hi.hiitem.R
import com.tuyrt.hi.hiitem.fragment.SecondFragment
import com.tuyrt.hi.hiitem.fragment.ThirdFragment
import kotlinx.android.synthetic.main.activity_act_demo.*

/**
 * author: Administrator on 2021/5/31.
 * desc:
 */
class ActDemoActivity : AppCompatActivity() {

    private var mFragments: List<Fragment> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_act_demo)

        val firstFragment = FirstFragment()
        val secondFragment = SecondFragment()
        val thirdFragment = ThirdFragment()

        /* val fragment = supportFragmentManager.findFragmentByTag(FIRST_FRAGMENT)
         if (fragment == null) {
             supportFragmentManager
                 .beginTransaction()
                 *//* .add(R.id.container, secondFragment)
                 .replace(R.id.container, thirdFragment)
                 .remove(thirdFragment)
                 .remove(secondFragment)*//*
                .add(R.id.container, firstFragment, FIRST_FRAGMENT)
                //.addToBackStack(null)
                .commit()
        }*/

        mFragments = listOf(firstFragment, secondFragment, thirdFragment)

        view_pager.adapter = MyFragmentStateAdapter()
        view_pager.orientation = ViewPager2.ORIENTATION_HORIZONTAL

        //监听前后台变化
        ActivityManager.instance.addFrontBackCallback(frontBackCallback)
    }

    inner class MyFragmentStateAdapter : FragmentStateAdapter(this) {

        override fun getItemCount(): Int {
           return mFragments.size
        }

        override fun createFragment(position: Int): Fragment {
            return mFragments[position]
        }
    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
    }

    val frontBackCallback = object : ActivityManager.FrontBackCallback {
        override fun onChanged(front: Boolean) {
            val state: String;
            if (front) {
                state = "前台"
            } else {
                state = "后台"
            }

            Toast.makeText(applicationContext, "当前处于：" + state, Toast.LENGTH_LONG).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityManager.instance.removeFrontBackCallback(frontBackCallback)
    }
}